<?php

namespace App\Http\Traits;

trait ApiResponse
{
    /**
     * 成功响应
     *
     * @param mixed $data
     * @param string $message
     * @param int $code
     * @param array $meta 额外的元数据（如分页信息）
     * @return \Illuminate\Http\JsonResponse
     */
    protected function success($data = null, string $message = '操作成功', int $code = 200, array $meta = [])
    {
        $response = [
            'code' => $code,
            'message' => $message,
        ];

        if ($data !== null) {
            $response['data'] = $data;
        }

        if (!empty($meta)) {
            $response['meta'] = $meta;
        }

        return response()->json($response, 200);
    }

    /**
     * 错误响应
     *
     * @param string $message
     * @param int $code
     * @param mixed $errors
     * @return \Illuminate\Http\JsonResponse
     */
    protected function error(string $message = '操作失败', int $code = 400, $errors = null)
    {
        $response = [
            'code' => $code,
            'message' => $message,
        ];

        if ($errors !== null) {
            $response['errors'] = $errors;
        }

        $httpCode = $code >= 200 && $code < 600 ? $code : 400;
        return response()->json($response, $httpCode);
    }

    /**
     * 验证失败响应
     *
     * @param \Illuminate\Contracts\Validation\Validator $validator
     * @return \Illuminate\Http\JsonResponse
     */
    protected function validationError($validator)
    {
        return $this->error('验证失败', 422, $validator->errors());
    }

    /**
     * 未授权响应
     *
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    protected function unauthorized(string $message = '未授权访问')
    {
        return $this->error($message, 401);
    }

    /**
     * 禁止访问响应
     *
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    protected function forbidden(string $message = '无权限访问')
    {
        return $this->error($message, 403);
    }

    /**
     * 未找到响应
     *
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    protected function notFound(string $message = '资源不存在')
    {
        return $this->error($message, 404);
    }
}

